package com.whut.whw.post;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.whut.whw.R;
import com.whut.whw.base.BaseActivity;
import com.whut.whw.bean.GoodsType;
import com.whut.whw.model.BackResult;
import com.whut.whw.util.BackResultCallback;
import com.whut.whw.util.GsonUtils;
import com.whut.whw.util.LogUtils;
import com.whut.whw.util.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;

import static com.whut.whw.constant.ConfigConsts.BASE_URL;

/**
 * Created by 张芳容 on 2017/06/12.
 */

public class Goods_typeSelectActivity extends BaseActivity {
    String goods_type;
    private List<GoodsType> first = new ArrayList<GoodsType>();
    private ArrayList<List<GoodsType>> second = new ArrayList<List<GoodsType>>();
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.refresh_list_view)
    ExpandableListView refresh_list_view;
    @BindView(R.id.loadingBar)
    ProgressBar loadingBar;

    @Override
    public int getLayoutId() {
        return R.layout.activity_area_select;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        initToolbar();
        loadingBar.setVisibility(View.INVISIBLE);
        String url = BASE_URL + "GetGoods_type/GetGoods_type";
        PostFormBuilder postFormBuilder = OkHttpUtils.post();
        postFormBuilder.url(url);
        postFormBuilder.build().execute(new BackResultCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                getUiDelegate().toastLong(e.toString());
                Log.e("获取物品类型", e.toString());
            }

            @Override
            public void onResponse(BackResult response, int id) {
                //如果获取数据成功
                if (response.isSuccess()) {
                    try {
                        LogUtils.e("物品", response.getData());
                        LogUtils.e("物品", response.getMsg());
                        first= GsonUtils.jsonToList(response.getData(),GoodsType.class);
                        second=GsonUtils.GsonToArrayList(response.getMsg(),new TypeToken<ArrayList<List<GoodsType>>>(){});
                    } catch (Exception e) {
                        LogUtils.e("物品", e.toString());
                    }
                    //示例
                    final ExpandableListAdapter adapter = new BaseExpandableListAdapter() {
                        // 获取指定组位置、指定子列表项处的子列表项数据
                        @Override
                        public Object getChild(int groupPosition, int childPosition) {
                            return second.get(groupPosition).get(childPosition);
                        }

                        @Override
                        public long getChildId(int groupPosition, int childPosition) {
                            return childPosition;
                        }

                        @Override
                        public int getChildrenCount(int groupPosition) {
                            return second.get(groupPosition).size();
                        }

                        private TextView getGroupTextView() {
                            AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                                    ViewGroup.LayoutParams.MATCH_PARENT, 130);
                            TextView textView = new TextView(Goods_typeSelectActivity.this);
                            textView.setLayoutParams(lp);
                            textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                            textView.setPadding(40, 0, 0, 0);
                            textView.setTextSize(16);
                            textView.setTextColor(ContextCompat.getColor(context, R.color.text_444));
                            return textView;
                        }

                        private TextView getChildTextView() {
                            AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                                    ViewGroup.LayoutParams.MATCH_PARENT, 110);
                            TextView textView = new TextView(Goods_typeSelectActivity.this);
                            textView.setLayoutParams(lp);
                            textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                            textView.setPadding(60, 0, 0, 0);
                            textView.setTextSize(14);
                            textView.setTextColor(ContextCompat.getColor(context, R.color.text_666));
                            return textView;
                        }

                        private ImageView getDivider() {
                            AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                                    ViewGroup.LayoutParams.MATCH_PARENT, 1);
                            ImageView imageView = new ImageView(Goods_typeSelectActivity.this);
                            imageView.setBackgroundColor(ContextCompat.getColor(context, R.color.text_999));
                            return imageView;
                        }

                        // 该方法决定每个子选项的外观
                        @Override
                        public View getChildView(int groupPosition, int childPosition,
                                                 boolean isLastChild, View convertView, ViewGroup parent) {
                            TextView textView = getChildTextView();
                            textView.setText(((GoodsType) getChild(groupPosition, childPosition)).getLbmc());
                            textView.setTag(((GoodsType) getChild(groupPosition, childPosition)).getLbbm());
                            return textView;
                        }

                        // 获取指定组位置处的组数据
                        @Override
                        public Object getGroup(int groupPosition) {
                            return first.get(groupPosition);
                        }

                        @Override
                        public int getGroupCount() {
                            return first.size();
                        }

                        @Override
                        public long getGroupId(int groupPosition) {
                            return groupPosition;
                        }

                        // 该方法决定每个组选项的外观
                        @Override
                        public View getGroupView(int groupPosition, boolean isExpanded,
                                                 View convertView, ViewGroup parent) {
                            DisplayMetrics dm = getResources().getDisplayMetrics();
                            int width = dm.widthPixels;
                            // ToastUtils.showShort("长度是"+width);
                            refresh_list_view.setIndicatorBounds(width - 40, width);
                            LinearLayout ll = new LinearLayout(Goods_typeSelectActivity.this);
                            TextView textView = getGroupTextView();
                            textView.setText(((GoodsType) getGroup(groupPosition)).getLbmc());
                            textView.setTag(((GoodsType) getGroup(groupPosition)).getLbbm());
                            ll.addView(textView);
                            return ll;
                        }

                        @Override
                        public boolean isChildSelectable(int groupPosition,
                                                         int childPosition) {
                            return true;
                        }

                        @Override
                        public boolean hasStableIds() {
                            return true;
                        }
                    };
                    refresh_list_view.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
                        @Override
                        public void onGroupExpand(int groupPosition) {
                            for (int i = 0; i < adapter.getGroupCount(); i++) {
                                if (groupPosition != i) {
                                    refresh_list_view.collapseGroup(i);
                                }
                            }
                        }
                    });
                    refresh_list_view.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
                        /**  * 参数1：控件的父对象  * 参数2：子的行布局对象  * 参数3：子节点所在的组的索引 * 参数4：子节点的索引
                         */
                        @Override
                        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                            Intent intent = getIntent();
                            Bundle bundle = new Bundle();
                            bundle.putString("first", ((GoodsType) (adapter.getGroup(groupPosition))).getLbbm());
                            bundle.putString("second", ((GoodsType) (adapter.getChild(groupPosition, childPosition))).getLbmc());
                            bundle.putString("code", ((GoodsType) (adapter.getChild(groupPosition, childPosition))).getLbbm());
                            //再把bundle中的数据传给intent，以传输过去
                            intent.putExtras(bundle);
                            setResult(RESULT_OK, intent);
                            finish();
                            return true;
                        }
                    });
                    refresh_list_view.setAdapter(adapter);

                } else {
                    Snackbar.make(refresh_list_view, response.getMsg(), Snackbar.LENGTH_LONG).show();
                }

            }
        });

    }

    /**
     * 初始化toolbar
     */
    private void initToolbar() {
        toolbar.setNavigationIcon(R.drawable.rc_back_icon);
        toolbar.setTitle(R.string.good_type_hint);
        toolbar.setTitleTextColor(ContextCompat.getColor(context, R.color.white));
    }

    private void initGoods_type() {
        String url = BASE_URL + "GetGoods_type/GetGoods_type";
        PostFormBuilder postFormBuilder = OkHttpUtils.post();
        postFormBuilder.url(url);
        postFormBuilder.build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.showLong("error->" + e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                //ToastUtils.showLong(response);
                goods_type = response;
            }
        });
    }

    @Override
    public void setListener() {
        //点击返回
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Goods_typeSelectActivity.this.finish();
            }
        });

    }

}
